import requests
import json
from ast import literal_eval
from echart.models import AiImgModel
from vis_sys.settings import BASE_DIR

BASE_URL = "http://172.16.8.85:8866"


def handle_uploaded_file(f, file_name):
    try:
        with open(file_name, 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)
    except Exception as e:
        print(e)
        return None
    return file_name

def get_model():
    # 获取当前可用模型
    url = f"{BASE_URL}/get/modules"
    r = requests.post(url=url)
    return json.dumps(r.json())


def trans_api(key, dest='zh-CN'):
    # Google翻译
    # 多个词语翻译
    # Example : "tension; Time; Doc; Big; OK; build"
    if isinstance (key,list):
        key = "; ".join(key)
    print(key)
    url = f"http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl={dest}&q={key}"
    r = requests.get(url=url)
    if r.status_code == 200:
        res = r.json()
        if len(res['sentences']) == 1:
            return [res['sentences'][0]['trans']]
        response = []
        for word in res['sentences']:
            response.append(word["trans"].replace(";",""))
        return response

def class_image(img_class):
    # 指定要预测的图片并生成列表[("image", img_1), ("image", img_2), ... ]
    files = [("image", img_class.photo)]
    # 指定预测方法为vgg11_imagenet并发送post请求
    url = f"{BASE_URL}/predict/image/xception71_imagenet"
    r = requests.post(url=url, files=files)
    # 打印预测结果
    r = r.json()
    if r['status'] == "0":
        results = literal_eval(r['results'])
        return results
    return []

def rubbish(key):
    # 自身一个垃圾分类接口
    url = f"http://server.foshanplus.com/rubbish?key={key}"
    print('url', url)
    res = requests.get(url)
    return res.json()

if __name__ == '__main__':
    print(rubbish('电池'))